# -*- coding: utf-8 -*-
import ZEO
import ZODB
import transaction
from persistent.list import PersistentList

from .models.folder import Folder
from .models.document import Document

from . import zeo_config


# http://www.fprimex.com/coding/zodb.html
class MyClient(object):
    """docstring for MyClient"""
    def __init__(self):
        super(MyClient).__init__()
        _address = zeo_config['port'].split(':')
        self.address = (_address[0], int(_address[1]))
        self.storage = None
        self.db = None
        self.transaction = None
        self.connection = None
        self.root = None
    
    def open(self):
        self.storage = ZEO.client(self.address)
        self.db = ZODB.DB(self.storage)
        self.transaction = transaction.TransactionManager()
        self.connection = self.db.open(self.transaction)
        self.root = self.connection.root()

        self.init_data()

    def close(self):
        if not self.connection is None:
            self.connection.close()
            self.root = None
            self.connection = None
            self.transaction = None
        if not self.db is None:
            self.db.close()
            self.db = None
        if not self.storage is None:
            self.storage.close()
            self.storage = None

    def commit(self):
        # http://zodb.readthedocs.io/en/latest/transactions.html
        self.transaction.commit()

    def abort(self):
        self.transaction.abort()

    def init_data(self):
        tree_key = Folder.tree_key()
        if not tree_key in self.root:
            root_key = Folder.tree_root_key()
            tree_root = Folder(root_key)
            self.root[tree_key] = tree_root
            self.root._p_changed = True
            self.commit()
        book_key = Document.book_key()
        if not book_key in self.root:
            self.root[book_key] = PersistentList()
            self.root._p_changed = True
            self.commit()